import {
  findWeightPage,
  findWeightList
} from '../../api/weightApi';
import * as echarts from '../../ec-canvas/echarts';
import {
  addDate,
  compareDate,
  compareYearMonth
} from '../../utils/dateUtil';
import {
  formatTimeByMothAndDay,
  formatTimeByYearAndMoth
} from '../../utils/formatUtil';
import storageUtil from '../../utils/storageUtil';
import shareUtil from './../../utils/shareUtil'

const app = getApp();
let chart = null;





Page({
  data: {
    // 系统平台
    system: app.globalData.system,
    // 导航栏高度
    navigationHeight: app.globalData.navigationHeight,
    // 统一背景颜色
    unifyBgColor: app.globalData.unifyBgColor,
    // 顶部导航栏高度
    topNavigationHeight: app.globalData.topNavigationHeight,
    // 主色调
    mainColor: app.globalData.mainColor,
    // ec 用于折线展示的数据
    ec: {},
    // 体重集合
    weightList: [],
    // 统计类型集合
    typeList: [{
      name: "近一月",
      value: "last_one_mouth",
    }, {
      name: "近三月",
      value: "last_three_mouth",
    }, {
      name: "近一年",
      value: "last_one_year",
    }, {
      name: "近五年",
      value: "last_five_year",
    }],
    // 类型下标
    typeIndex: 0,
    // 没有数据标志
    noDataFlag: false
  },

  onLoad() {
    // 开启微信内置分享功能
    shareUtil.startShare()

    // 设置折线展示的数据
    this.setData({
      ec: {
        onInit: this.initChart
      }
    })

    setTimeout(() => {
      this.setData({
        noDataFlag: true
      })
    }, 2000);
  },

  // 分享给朋友
  onShareAppMessage() {
    return shareUtil.shareToFreind()
  },

  // 查找全部体重数据
  findAllWeight() {
    let form = {}
    // 根据何值分组
    let typeIndex = this.data.typeIndex
    if (typeIndex == 0) {
      form.groupField = "date"
      form.date = new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 30)
    } else if (typeIndex == 1) {
      form.groupField = "date"
      form.date = new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 30 * 3)
    } else if (typeIndex == 2) {
      form.groupField = "yearMonth"
      form.date = new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 30 * 12 * 1)
    } else {
      form.groupField = "yearMonth"
      form.date = new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 30 * 12 * 5)
    }
    form.openid = storageUtil.getStorage("openId")
    console.log("form : ", form)
    findWeightList(form).then((res) => {
      console.log(res)
      let data = res.list
      let weightList = this.data.weightList
      weightList = data
      this.setData({
        weightList: weightList
      })
      // 设置初始化函数
      this.resetOption()



    })
  },

  // 折线图初始化
  initChart(canvas, width, height, dpr) {
    // 初始化
    chart = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr // new
    });
    canvas.setChart(chart);

    // 查找体重数据
    this.findAllWeight()
    return chart;
  },

  // 设置折线数据
  resetOption() {
    let typeIndex = this.data.typeIndex
    let xList = []
    let valueList = []
    console.log('typeIndex : ', typeIndex)
    if (typeIndex == 0 || typeIndex == 1) {
      xList = this.getDateXList()
      valueList = this.getDateValueList(xList.length)
    } else {
      xList = this.getMonthXList()
      valueList = this.getMonthValueList(xList.length)
    }

    // 设置数据
    var option = {
      grid: {
        containLabel: true
      },
      tooltip: {
        show: true,
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        //data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        data: xList,
        // show: false
        //boundaryGap: false, // 距离坐标原点是否有间隙
        axisLabel: { //  如果这个字段不设置，echarts会根据屏宽及横坐标数据自动给出间隔
          //interval: 30, // 间隔长度，可自定义（如果是时间格式，echarts会自动处理）
          //rotate: 40 // 横坐标上label的倾斜度
        },
      },
      yAxis: {
        type: 'value',
        name: '体重',
        axisLine: {
          show: true
        },
        axisTick: {
          length: 1,
          lineStyle: {
            type: 'dashed'
            // ...
          }
        },
        min: function (value) {
          return value.min - 2;
        },
        max: function (value) {
          return value.max + 2;
        },
        position: 'left'
      },
      series: [{
        name: 'A',
        type: 'line',
        // series.dimensions 会更优先于 dataset.dimension 采纳。
        smooth: true,
        //data: [18, 36, 65, 30, 78, 40, 33]
        data: valueList
      }]
    };
    console.log("option : ", option)
    // 设置数据
    chart.setOption(option);
  },

  // 获得x坐标集合
  getDateXList() {
    let weightList = this.data.weightList
    let xList = []
    // for (let i = 0; i < weightList.length; i++) {
    //   let item = weightList[i]
    //   //xList.push(item.dateTime)
    //   xList.push(item.dateTime)
    // }
    // 没有数据
    if (weightList.length == 0) {
      return xList
    }
    // 只有一个
    if (weightList.length == 1) {
      xList.push(formatTimeByMothAndDay(weightList[0].dateTime))
      return xList
    }
    let startTime = weightList[0].dateTime
    let startTimeStamp = startTime.getTime()
    let lastTime = weightList[weightList.length - 1].dateTime
    lastTime.setHours(23, 59, 59, 999)
    let lastTimeStamp = lastTime.getTime()
    let typeIndex = this.data.typeIndex
    for (; startTimeStamp < lastTimeStamp; startTimeStamp = startTimeStamp + 60 * 60 * 24 * 1000) {
      xList.push(formatTimeByMothAndDay(new Date(startTimeStamp)))
    }
    console.log("xList : ", xList)
    return xList
  },

  // 获得x坐标集合
  getMonthXList() {
    let weightList = this.data.weightList
    let xList = []

    // 没有数据
    if (weightList.length == 0) {
      return xList
    }
    // 只有一个
    if (weightList.length == 1) {
      xList.push(formatTimeByMothAndDay(weightList[0].dateTime))
      return xList
    }
    let startTime = new Date(weightList[0].date)
    let lastTime = new Date(weightList[weightList.length - 1].date)
    // 设置为下个月的第一天第0秒
    // 增加一个月
    lastTime = addDate(lastTime, 0, 1)
    // 设置为第一天
    lastTime.setDate(1)
    // 设置为第0秒
    lastTime.setHours(0, 0, 0, 0)
    for (; compareDate(startTime, lastTime) < 0; startTime = this.getNextMonth(startTime)) {
      xList.push(formatTimeByYearAndMoth(new Date(startTime)))
    }
    console.log("xList : ", xList)
    return xList
  },

  // 获得下一个月的时间
  getNextMonth(date) {
    // 增加一个月时间
    date = addDate(date, 0, 1)
    console.log('next month : ', formatTimeByYearAndMoth(date))
    return date
  },

  // 获得x坐标的值集合
  getMonthValueList(maxLength) {
    let weightList = this.data.weightList
    let valueList = []
    // for (let i = 0; i < weightList.length; i++) {
    //   let item = weightList[i]
    //   //xList.push(item.dateTime)
    //   xList.push(item.dateTime)
    // }
    // 没有数据
    if (weightList.length == 0) {
      return valueList
    }
    // 只有一个
    if (weightList.length == 1) {
      valueList.push(weightList[0].weight)
      return valueList
    }
    let startTime = new Date(weightList[0].date)
    let startTimeStamp = startTime.getTime()
    let lastTime = new Date(weightList[weightList.length - 1].dateTime)
    // 设置为下个月的第一天第0秒
    // 增加一个月
    lastTime = addDate(lastTime, 0, 1)
    // 设置为第一天
    lastTime.setDate(1)
    // 设置为第0秒
    lastTime.setHours(0, 0, 0, 0)
    // 体重数据下标
    let weightIndex = 0
    for (; compareYearMonth(startTime, lastTime) <= 0 && valueList.length < maxLength; startTime = this.getNextMonth(startTime)) {
      console.log('weightIndex : ', weightIndex)
      console.log('startTime : ', formatTimeByYearAndMoth(startTime))
      console.log('lastTime : ', formatTimeByYearAndMoth(lastTime))
      // 体重item
      let itemWeight = weightList[weightIndex]
      let weightDate = new Date(itemWeight.date)
      let topWeight = itemWeight.weight
      // 当前item的时间
      let compareValue = compareYearMonth(startTime, weightDate)
      if (compareValue == -1) {
        valueList.push(topWeight)
      } else if (compareValue == 0) {
        valueList.push(topWeight)
      } else {
        weightIndex++
        topWeight = weightList[weightIndex].weight
        startTime = addDate(startTime, 0, -1)
      }
    }
    console.log("valueList : ", valueList)
    return valueList
  },

  // 获得x坐标的值集合
  getDateValueList(maxLength) {
    let weightList = this.data.weightList
    let valueList = []
    // for (let i = 0; i < weightList.length; i++) {
    //   let item = weightList[i]
    //   //xList.push(item.dateTime)
    //   xList.push(item.dateTime)
    // }
    // 没有数据
    if (weightList.length == 0) {
      return valueList
    }
    // 只有一个
    if (weightList.length == 1) {
      valueList.push(weightList[0].weight)
      return valueList
    }
    let startTime = weightList[0].dateTime
    let startTimeStamp = startTime.getTime()
    let lastTime = weightList[weightList.length - 1].dateTime
    lastTime.setHours(23, 59, 59, 999)
    let lastTimeStamp = lastTime.getTime()
    let topWeight = weightList[0].weight
    let weightIndex = 0
    for (; startTimeStamp <= lastTimeStamp && valueList.length < maxLength; startTimeStamp = startTimeStamp + 60 * 60 * 24 * 1000) {
      let itemWeight = weightList[weightIndex]
      let weightDate = itemWeight.dateTime
      let itemDate = new Date(startTimeStamp)
      let compareValue = compareDate(itemDate, weightDate)
      if (compareValue == -1) {
        valueList.push(topWeight)
      } else if (compareValue == 0) {
        valueList.push(topWeight)
      } else {
        weightIndex++
        topWeight = weightList[weightIndex].weight
        startTimeStamp = startTimeStamp - 60 * 60 * 24 * 1000
      }
    }
    console.log("valueList : ", valueList)
    return valueList
  },

  // 选择分类下标
  selectType(e) {
    console.log(e)
    let index = e.currentTarget.dataset.index
    if (index == this.data.typeIndex) {
      return
    }
    this.setData({
      typeIndex: index
    })
    // 刷新折线图
    this.findAllWeight()
  }


});